package com.zzzzzz.core.data.filestore;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.aliyun.openservices.ClientConfiguration;
import com.aliyun.openservices.ClientException;
import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.OSSException;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;

public class OSSFileStorage implements FileStorage {
	
	private final OSSClient client;
	private final String bucketName;

	public OSSFileStorage(String accessId, String accessKey, String endpoint, String bucketName) {
		ClientConfiguration config = new ClientConfiguration();
        client = new OSSClient(endpoint, accessId, accessKey, config);
        this.bucketName = bucketName;
	}
	
	public String storeFile(FileData fileData) {
		try {
	        ObjectMetadata objectMetadata = new ObjectMetadata();
	        objectMetadata.setContentLength(fileData.getBytes().length);
	        objectMetadata.setContentType(fileData.getContentType());
	
	        ByteArrayInputStream bis = new ByteArrayInputStream(fileData.getBytes());
	        PutObjectResult putObjectResult = client.putObject(bucketName, fileData.getName(), bis, objectMetadata);
	        //putObjectResult.getETag();
		} catch (OSSException e) {
			throw new RuntimeException("Unable to put object into OSS", e);
		} catch (ClientException e) {
			throw new RuntimeException("Unable to put object into OSS", e);
		}
		
		return fileData.getName();
	}

	public InputStream getFile(String fileName) {
		 return client.getObject(bucketName, fileName).getObjectContent();
	}

	public void removeFile(String fileName) {
		client.deleteObject(bucketName, fileName);
	}
	
}
